import { defineConfig, type UserConfigExport } from '@tarojs/cli'
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin'
import devConfig from './dev'
import prodConfig from './prod'
import path from 'path'
import { DefinePlugin } from 'webpack'
import dayjs from "dayjs";

// https://taro-docs.jd.com/docs/next/config#defineconfig-辅助函数
export default defineConfig<'webpack5'>(async (merge, { command, mode }) => {
    const baseConfig: UserConfigExport<'webpack5'> = {
        projectName: '2',
        date: '2025-7-29',
        designWidth: 375,
        deviceRatio: {
            640: 2.34 / 2,
            750: 1,
            375: 2,
            828: 1.81 / 2
        },
        sourceRoot: 'srcMiniprogram', // 修改此行，将'src'改为'srcMiniprogram'
        outputRoot: 'dist-miniprogram',
        // 添加额外源码目录
        // extraSourceRoot: ['api'],
        plugins: [
            '@tarojs/plugin-html',
            '@tarojs/plugin-http',
        ],
        defineConstants: {
        },
        copy: {
            patterns: [
            ],
            options: {
            }
        },
        framework: 'react',
        compiler: {
            type: 'webpack5',
            prebundle: {
                enable: false
            }
        },
        cache: {
            enable: false,
        },
        mini: {
            postcss: {
                url: {
                    enable: false
                },
                pxtransform: {
                    enable: true,
                    config: {
                        selectorBlackList: ['nut-']
                    }
                },
                cssModules: {
                    enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
                    config: {
                        namingPattern: 'module', // 转换模式，取值为 global/module
                        generateScopedName: '[name]__[local]___[hash:base64:5]'
                    }
                }
            },
            webpackChain(chain) {
                chain.plugin('provide-react').use(require('webpack').ProvidePlugin, [{
                    React: 'react',
                    'ReactDOM': 'react-dom'
                }]);
                chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin);
                chain.resolve.alias.set('@', path.resolve(__dirname, '../'));
                // 扩展文件解析
                chain.resolve.extensions
                    .clear()
                    .merge(['.js', '.jsx', '.ts', '.tsx', '.json']);
                // 确保TypeScript文件被正确处理
                chain.module
                    .rule('script')
                    .test(/\.(js|jsx|ts|tsx)$/)
                    .include
                    .add(path.resolve(__dirname, '../srcMiniprogram'))
                    .add(path.resolve(__dirname, '../api'))
                    .add(path.resolve(__dirname, '../utils'))
                    .add(path.resolve(__dirname, '../srcService'))
                    .end()
                    .use('babel-loader')
                    .loader(require.resolve('babel-loader'))
                    .options({
                        presets: [
                            require.resolve('@babel/preset-typescript'),
                            [require.resolve('@babel/preset-env'), { targets: { node: 'current' } }],
                            [require.resolve('@babel/preset-react')]
                        ],
                        plugins: [
                            [require.resolve('@babel/plugin-transform-runtime')],
                            [require.resolve('@babel/plugin-transform-class-properties')],
                            [require.resolve('@babel/plugin-transform-private-methods')]
                        ],
                        babelrc: false,
                        configFile: false
                    });
                // 添加编译时间定义
                chain.plugin('define-build-time').use(DefinePlugin, [{
                    'process.env.BUILD_TIME': JSON.stringify(dayjs().format("YYYY-MM-DD HH:mm:ss"))
                }]);
                // 添加文件大小限制
                chain.performance
                    .set('maxEntrypointSize', 1024 * 1024) // 1MB
                    .set('maxAssetSize', 1024 * 1024) // 1MB
                    .set('hints', 'warning');
            },

            imageUrlLoaderOption: {
                limit: -1 // 禁止将图片转换为 base64
            }
        },
        h5: {
            publicPath: '../srcMiniprogram',
            staticDirectory: 'public',
            output: {
                filename: 'js/[name].[hash:8].js',
                chunkFilename: 'js/[name].[chunkhash:8].js'
            },
            miniCssExtractPluginOption: {
                ignoreOrder: true,
                filename: 'css/[name].[hash].css',
                chunkFilename: 'css/[name].[chunkhash].css'
            },
            postcss: {
                autoprefixer: {
                    enable: true,
                    config: {}
                },
                cssModules: {
                    enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
                    config: {
                        namingPattern: 'module', // 转换模式，取值为 global/module
                        generateScopedName: '[name]__[local]___[hash:base64:5]'
                    }
                }
            },
            webpackChain(chain) {
                chain.plugin('provide-react').use(require('webpack').ProvidePlugin, [{
                    React: 'react',
                    'ReactDOM': 'react-dom'
                }]);
                chain.resolve.plugin('tsconfig-paths').use(TsconfigPathsPlugin)
                chain.resolve.alias.set('@', path.resolve(__dirname, '../'));
                // 添加编译时间定义
                chain.plugin('define-build-time').use(DefinePlugin, [{
                    'process.env.BUILD_TIME': JSON.stringify(dayjs().format("YYYY-MM-DD HH:mm:ss"))
                }]);
                // 添加文件大小限制
                chain.performance
                    .set('maxEntrypointSize', 1024 * 1024) // 1MB
                    .set('maxAssetSize', 1024 * 1024) // 1MB
                    .set('hints', 'warning');
            },
            imageUrlLoaderOption: {
                limit: -1 // 禁止将图片转换为 base64
            }
        },
        rn: {
            appName: 'taroDemo',
            postcss: {
                cssModules: {
                    enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
                }
            }
        }
    }
    if (process.env.NODE_ENV === 'development') {
        // 本地开发构建配置（不混淆压缩）
        return merge({}, baseConfig, devConfig)
    }
    // 生产构建配置（默认开启压缩混淆等）
    return merge({}, baseConfig, prodConfig)
})